{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-08-18T12:25:25.378733Z",
     "start_time": "2025-08-18T12:25:18.154973Z"
    }
   },
   "source": [
    "from langchain_openai import ChatOpenAI\n",
    "from langchain_core.prompts import PromptTemplate\n",
    "import os\n",
    "chat_model = ChatOpenAI(\n",
    "    # 若没有配置环境变量，请用百炼API Key将下行替换为：api_key=\"sk-xxx\",\n",
    "    api_key=os.getenv(\"DASH_SCOPE_API_KEY\"), # 如何获取API Key：https://help.aliyun.com/zh/model-studio/developer-reference/get-api-key\n",
    "    base_url=\"https://dashscope.aliyuncs.com/compatible-mode/v1\",\n",
    "    model=\"qwen-plus\",\n",
    "    temperature=0.8,\n",
    "    max_tokens=60,\n",
    ")\n",
    "\n",
    "# 导入结构化输出解析器和ResponseSchema\n",
    "from langchain.output_parsers import StructuredOutputParser, ResponseSchema\n",
    "# 定义我们想要接收的响应模式\n",
    "response_schemas = [\n",
    "    ResponseSchema(name=\"description\", description=\"鲜花的描述文案\"),\n",
    "    ResponseSchema(name=\"reason\", description=\"问什么要这样写这个文案\")\n",
    "]\n",
    "\n",
    "# 创建输出解析器\n",
    "output_parser = StructuredOutputParser.from_response_schemas(response_schemas)\n",
    "\n",
    "# 获取格式指示\n",
    "format_instructions = output_parser.get_format_instructions()\n",
    "\n",
    "# 创建提示模板\n",
    "prompt_template = \"\"\"您是一位专业的鲜花店文案撰写员。\\n\n",
    "对于售价为 {price} 元的 {flower_name} ，您能提供一个吸引人的简短描述吗？\n",
    "{format_instructions}\"\"\"\n",
    "\n",
    "# 导入结构化输出解析器和ResponseSchema\n",
    "prompt = PromptTemplate.from_template(prompt_template, \n",
    "                partial_variables={\"format_instructions\": format_instructions}) \n",
    "\n",
    "# 打印LangChain提示模板的内容\n",
    "print(prompt)\n",
    "\n",
    "# 多种花的列表\n",
    "flowers = [\"玫瑰\", \"百合\", \"康乃馨\"]\n",
    "prices = [\"50\", \"30\", \"20\"]\n",
    "\n",
    "# 创建一个空的DataFrame用于存储结果\n",
    "import pandas as pd\n",
    "df = pd.DataFrame(columns=[\"flower\", \"price\", \"description\", \"reason\"]) # 先声明列名\n",
    "\n",
    "for flower, price in zip(flowers, prices):\n",
    "    # 根据提示准备模型的输入\n",
    "    input_message = prompt.format(flower_name=flower, price=price)\n",
    "    \n",
    "    # 获取模型的输出\n",
    "    output = chat_model.invoke(input_message)\n",
    "    \n",
    "    # 输出结果打印\n",
    "    # print(output)\n",
    "     # 解析模型的输出（这是一个字典结构）\n",
    "    parsed_output = output_parser.parse(output.content.strip())\n",
    "    \n",
    "    # 在解析后的输出中添加“flower”和“price”\n",
    "    parsed_output['flower'] = flower\n",
    "    parsed_output['price'] = price\n",
    "    \n",
    "    # 将解析后的输出添加到DataFrame中\n",
    "    df.loc[len(df)] = parsed_output\n",
    "    \n",
    "# 打印字典\n",
    "df\n",
    "print(df.to_dict(orient='records'))"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "input_variables=['flower_name', 'price'] input_types={} partial_variables={'format_instructions': 'The output should be a markdown code snippet formatted in the following schema, including the leading and trailing \"```json\" and \"```\":\\n\\n```json\\n{\\n\\t\"description\": string  // 鲜花的描述文案\\n\\t\"reason\": string  // 问什么要这样写这个文案\\n}\\n```'} template='您是一位专业的鲜花店文案撰写员。\\n\\n对于售价为 {price} 元的 {flower_name} ，您能提供一个吸引人的简短描述吗？\\n{format_instructions}'\n",
      "[{'flower': '玫瑰', 'price': '50', 'description': '50元的浪漫承诺，一朵玫瑰，传递一心一意的爱意。', 'reason': '通过强调价格与情感价值的结合，将简单的玫瑰与深情的寓意联系起来，吸引想要表达爱意又追求性价比的顾客。'}, {'flower': '百合', 'price': '30', 'description': '纯净如初见，百合以柔美姿态传递你心中的真挚情感。', 'reason': '该文案通过‘纯净如初见’唤起百合象征的纯洁与真挚情感，同时用‘柔美姿态’突出了百合的视觉美感和情感价值，激发顾客购买欲望。'}, {'flower': '康乃馨', 'price': '20', 'description': '温馨满溢，母爱如花——20元让康乃馨传递你的心意。', 'reason': '康乃馨是表达爱与感恩的经典象征，尤其与母亲节等情感节日紧密相关。通过强调情感价值与亲民价格，吸引顾客用一束鲜花传递深情。'}]\n"
     ]
    }
   ],
   "execution_count": 13
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": "",
   "id": "11d61aa5eaff935f"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
